import { defineStore } from 'pinia';
import { local } from '@/utils/storage';
import { IAuth } from '@/store/types';
import { store } from '@/store';
import { IForgotPasswordParam, ISmsLoginParam, IUserLoginParam } from '@/api/types';
import { reqForgotPassword, reqSmsLogin, reqUserLogin } from '@/api/module/userApi';
import { ElMessage } from 'element-plus';
import { useUserinfoStore } from '@/store/module/useUserStore';
import { RouteLocationNormalized, Router } from 'vue-router';
import { useGo, useRedo } from '@/hooks/router';
import { HeaderRouterPath } from '@/router/types';

const AUTH = 'auth';
const defAuth: IAuth = { token: '', tokenHead: '', userId: 0, username: '' };
const authSetting = local.get<IAuth>(AUTH, defAuth);

export const useAuthStore = defineStore(AUTH, {
  state: (): IAuth => authSetting,
  getters: {
    getToken(): string {
      return this.tokenHead + ' ' + this.token;
    },
  },
  actions: {
    isLogged() {
      return !!this.token && !!this.userId;
    },
    load(data: IAuth) {
      this.$patch({ ...data });
    },
    unload() {
      this.$patch({
        ...{ token: '', tokenHead: '', userId: 0, username: '' },
      });
    },
    smsLogin(param: ISmsLoginParam, router: Router, callback?: Function) {
      reqSmsLogin(param)
        .then((res) => {
          const { data, msg } = res;
          callback && callback();
          ElMessage({ message: msg, type: 'success' });
          this.load(data);
          this.loginAfterActions(router);
        })
        .catch(() => {
          callback && callback();
        });
    },
    userLogin(param: IUserLoginParam, router: Router, callback?: Function) {
      reqUserLogin(param)
        .then((res) => {
          const { data, msg } = res;
          callback && callback();
          ElMessage({ message: msg, type: 'success' });
          this.load(data);
          this.loginAfterActions(router);
        })
        .catch(() => {
          callback && callback();
        });
    },
    forgotPassword(param: IForgotPasswordParam, callback?: Function) {
      reqForgotPassword(param)
        .then((res) => {
          ElMessage({ message: res.msg, type: 'success' });
        })
        .catch(() => {})
        .finally(() => {
          callback && callback();
        });
    },
    loginAfterActions(router: Router) {
      const redirectName = router.currentRoute.value.query.redirect;
      const go = useGo(router);
      if (redirectName) {
        go({ name: redirectName }, true);
      } else {
        go(HeaderRouterPath.HOME, true);
      }
      const userinfoStore = useUserinfoStore();
      userinfoStore.getUserinfo();
    },
    logout(callback?: Function) {
      const userStore = useUserinfoStore();
      userStore.unload();
      this.unload();
      local.clear();
      callback && callback();
    },
  },
});
/**
 * 在setup外使用store
 */
export const useAuthStoreWithOut = () => {
  return useAuthStore(store);
};

//添加订阅
const authStore = useAuthStoreWithOut();
authStore.$subscribe((mutation, state) => {
  local.set(mutation.storeId, JSON.stringify(state));
});
